package tv_megazineplus
import fb.FbUtil
import groovy.sql.Sql
import org.codehaus.groovy.runtime.TimeCategory
import groovy.time.TimeDuration

/*
 *Once a month, send a post to a user's FB with the topX programs
 *
 *
*/

class FbUserStatsJob {
    static triggers = {
    simple name: 'sendUserTopX', startDelay: 2592000000, repeatInterval: 2592000000  
  }

    def execute() {
        def userStats = []
        def textoS
        def users = Users.list()
        def dtInicio, dtFim
        
        
        
        use(TimeCategory){
        dtInicio = new Date() - 1.months
        dtFim = new Date() + 1.days
        }
        
        def sql = Sql.newInstance( 'jdbc:postgresql://localhost:5432/ad', 'postgres','postgres', 'org.postgresql.Driver' )
        users.each{
        userStats = []    
        def all = UserPrefs.findByUser(it)
            
            if(it.fbtoken != null && it.fbtoken != '' && all.postMural==true){
        sql.eachRow('select count(prog_title) contagem, prog_title,users.email from programmation join alert on programmation.id = alert.program_id join users on alert.user_id = users.id where users.email=\''+it.email+'\' and alert.hora_dispara between \''+dtInicio+'\' and \''+dtFim+'\' group by alert.user_id, prog_title,email order by contagem desc limit 10 ') {
           userStats.add(new UserStats(program_title:it.prog_title,user_email:it.email,frequencia:it.contagem))
        }
        if(userStats == null){
            
        }else{
            textoS = 'TvMEGAzineP Top ' + userStats.size() + ' Programms:\n\n'
            
            userStats.each{ us ->
                textoS = textoS + '\t\t\t\t - ' + us.program_title + '\n'
            }
            FbUtil fb = new FbUtil()        
                
                    fb.sendComent(it.fbtoken, textoS)
        }
                    }
         }       
    }
}
